//
//  SISSObtainEvidenceEnrollViewController.m
//  SISSAPP
//
//  Created by 袁应荣 on 2018/10/31.
//  Copyright © 2018年 优房网. All rights reserved.
//

#import "SISSObtainEvidenceEnrollViewController.h"
#import "SISSObtainEvidenceEnrollViewModel.h"
#import "SISSObtainEvidenceShowViewController.h"
#import "EBDropdownListView.h"
#import "SISSDatePickerView.h"
#import "SISSNetworkingManager+HouseProgress.h"

@interface SISSObtainEvidenceEnrollViewController ()<SISSDatePickerViewDelegate>

@property (weak, nonatomic) UIButton *timeChooseButton;

@property (weak, nonatomic) UIButton *confirmButton;

@property (strong, nonatomic) SISSObtainEvidenceEnrollViewModel *obtainEvidenceEnrollViewModel;
@property (assign, nonatomic) SISSObtainEvidenceEnrollModel *obtainEvidenceEnrollModel;

@property (copy, nonatomic) NSString *dateStr;
@property (copy, nonatomic) NSString *timeQuantum;
@property (strong, nonatomic) NSDate *date;

@end

@implementation SISSObtainEvidenceEnrollViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.date = [NSDate new];
    self.title = @"录入取证信息";
}
#pragma mark - SISSDatePickerViewDelegate
- (void)determine:(SISSDatePickerView *)choose date:(NSDate *)date {
    
    NSString *timeStr = [choose stringFromDate:date];
    NSLog(@"determine  %@",timeStr);
    //    self.timeView.rightStr = timeStr;
    [self.timeChooseButton setTitle:timeStr forState:UIControlStateNormal];
    [self.timeChooseButton setTitleColor:MAIN_TEXT_COLOR forState:UIControlStateNormal];
    self.dateStr = timeStr;
    self.date = date;
}

- (void)changeTime:(SISSDatePickerView *)choose date:(NSDate *)date {
    
    NSString *timeStr = [choose stringFromDate:date];
    NSLog(@"changeTime  %@",timeStr);
}

- (void)timeChooseButtonClickAction {
    [self.view endEditing:YES];
    SISSDatePickerView *datePickerView = [[SISSDatePickerView alloc] initWithType:UIDatePickerModeDate title:@"预约日期"];
    [datePickerView setNowTime:self.date];
    datePickerView.delegate = self;
}

#pragma mark - 代理
#pragma mark -- UITableViewDelegate & UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.obtainEvidenceEnrollViewModel getSectionCount];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.obtainEvidenceEnrollViewModel getRowsInSection:section];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [self.obtainEvidenceEnrollViewModel getCell:tableView indexPath:indexPath];
    if (indexPath.section == 0 && indexPath.row == 1) {
        UIButton *timeChooseButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [timeChooseButton setTitle:@"选择年月日" forState:UIControlStateNormal];
        [timeChooseButton setTitleColor:SECONDARY_TEXT_COLOR forState:UIControlStateNormal];
        timeChooseButton.titleLabel.font = [UIFont systemFontOfSize:15];
        [timeChooseButton.layer setBorderWidth:1];
        [timeChooseButton.layer setBorderColor:SECONDARY_TEXT_COLOR.CGColor];
        [timeChooseButton addTarget:self action:@selector(timeChooseButtonClickAction) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:timeChooseButton];
        self.timeChooseButton = timeChooseButton;
        
        
        EBDropdownListItem *item1 = [[EBDropdownListItem alloc] initWithItem:@"1" itemName:@"9:00-10:00"];
        EBDropdownListItem *item2 = [[EBDropdownListItem alloc] initWithItem:@"2" itemName:@"10:00-11:00"];
        EBDropdownListItem *item3 = [[EBDropdownListItem alloc] initWithItem:@"3" itemName:@"11:00-12:00"];
        EBDropdownListItem *item4 = [[EBDropdownListItem alloc] initWithItem:@"4" itemName:@"14:00-15:00"];
        EBDropdownListItem *item5 = [[EBDropdownListItem alloc] initWithItem:@"5" itemName:@"15:00-16:00"];
        EBDropdownListItem *item6 = [[EBDropdownListItem alloc] initWithItem:@"6" itemName:@"16:00-17:00"];
        
        
        EBDropdownListView *timeDropdownListView = [[EBDropdownListView alloc] init];
        timeDropdownListView.selectedIndex = 0;
        timeDropdownListView.dataSource = @[item1, item2, item3, item4, item5, item6];
        [timeDropdownListView setViewBorder:0.5 borderColor:[UIColor grayColor] cornerRadius:2];
        [cell.contentView addSubview:timeDropdownListView];
        [timeDropdownListView setDropdownListViewSelectedBlock:^(EBDropdownListView * _Nonnull dropdownListView) {
            NSString *msgString = [NSString stringWithFormat:
                                   @"selected name:%@  id:%@  index:%ld"
                                   , dropdownListView.selectedItem.itemName
                                   , dropdownListView.selectedItem.itemId
                                   , dropdownListView.selectedIndex];
            self.timeQuantum = dropdownListView.selectedItem.itemName;
            NSLog(@"%@",msgString);
        }];
        self.timeQuantum = item1.itemName;
        
        if (self.dataSource.count > 0) {
            SISSContractModel *model = self.dataSource[indexPath.section][indexPath.row];
            self.dateStr = model.rightStr.length > 10 ? [model.rightStr substringToIndex:10] : @"";
            self.timeQuantum = model.rightStr.length > 10 ? [[model.rightStr substringFromIndex:10] stringByReplacingOccurrencesOfString:@" " withString:@""] : @"";
            [self.timeChooseButton setTitle:self.dateStr forState:UIControlStateNormal];
            [self.timeChooseButton setTitleColor:MAIN_TEXT_COLOR forState:UIControlStateNormal];
            for (NSInteger i = 0; i < timeDropdownListView.dataSource.count; i++) {
                EBDropdownListItem *item = timeDropdownListView.dataSource[i];
                if ([self.timeQuantum isEqualToString:item.itemName]) {
                    timeDropdownListView.selectedIndex = [item.itemId integerValue] - 1;
                }
            }
        }
        
        UIView *bottomLine = [[UIView alloc] init];
        bottomLine.backgroundColor = [UIColor groupTableViewBackgroundColor];
        [cell.contentView addSubview:bottomLine];
        
        [timeChooseButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(cell.contentView);
            make.left.equalTo(cell.contentView).offset(14 * globelMargin);
            make.width.mas_equalTo(14 * globelMargin);
            make.height.mas_equalTo(3 * globelMargin);
        }];
        
        [timeDropdownListView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(cell.contentView);
            make.left.equalTo(timeChooseButton.mas_right).offset(globelMargin);
            make.right.equalTo(cell.contentView).offset(-2 * globelMargin);
            make.height.mas_equalTo(3 * globelMargin);
        }];
        
        [bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
            //        make.top.equalTo(weakSelf.textView.mas_bottom).offset(1.5 * margin);
            make.left.right.bottom.equalTo(cell.contentView);
            make.height.mas_equalTo(1);
        }];
    }
    //    NSArray *arr = self.dataArr[indexPath.section];
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return [self.obtainEvidenceEnrollViewModel getHeightForHeaderInSection:section];
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    return [self.obtainEvidenceEnrollViewModel getViewHeaderInSection:section];
}

// 取消tableView组头悬停
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat sectionHeaderHeight = 40;
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}

/**
 必选提示
 
 @return 返回YES时需要填写或选择
 */
- (BOOL)requiredTip {

    SISSObtainEvidenceEnrollModel *obtainEvidenceEnrollModel = [self.obtainEvidenceEnrollViewModel dataArrToObtainEvidenceEnrollModel];
    obtainEvidenceEnrollModel.obtainTime = [NSString stringWithFormat:@"%@ %@",self.dateStr,self.timeQuantum];
    if (!obtainEvidenceEnrollModel.bank || obtainEvidenceEnrollModel.bank.length == 0) {
        [SISSTools showSVErrorTitle:@"请输入取证银行" andTime:2 andColor:YES];
        return YES;
    }
    if (self.dateStr.length == 0) {
        [SISSTools showSVErrorTitle:@"请选择取证时间" andTime:2 andColor:YES];
        return YES;
    }
    if (!obtainEvidenceEnrollModel.address || obtainEvidenceEnrollModel.address.length == 0) {
        [SISSTools showSVErrorTitle:@"请输入取证地点" andTime:2 andColor:YES];
        return YES;
    }
    if (!obtainEvidenceEnrollModel.mortgage || obtainEvidenceEnrollModel.mortgage.length == 0) {
        [SISSTools showSVErrorTitle:@"请选择抵押登记情况" andTime:2 andColor:YES];
        return YES;
    }
    self.obtainEvidenceEnrollModel = obtainEvidenceEnrollModel;
    self.obtainEvidenceEnrollViewModel.dataArr[0][1].rightStr = obtainEvidenceEnrollModel.obtainTime;
    return NO;
}


#pragma mark - 按钮点击事件
#pragma mark -- 确定按钮点击事件
- (void)confirmButtonClickAction {
    
    if ([self requiredTip]) return;
    NSString *attention = self.obtainEvidenceEnrollModel.attention.length ? self.obtainEvidenceEnrollModel.attention : @"";
    NSString *otherdesc = self.obtainEvidenceEnrollModel.otherdesc.length ? self.obtainEvidenceEnrollModel.otherdesc : @"";
    
    if (self.dataSource.count > 0) {
        NSDictionary *paramters = @{
                                    @"id": self.mortgageInfoModel.ID,
                                    @"spId": [SISSUserAccount shared].spId,
                                    @"ahbpId": self.ahbpId,
                                    @"address": self.obtainEvidenceEnrollModel.address,
                                    @"bank": self.obtainEvidenceEnrollModel.bank,
                                    @"mortgage": self.obtainEvidenceEnrollModel.mortgage,
                                    @"obtainTime": self.obtainEvidenceEnrollModel.obtainTime,
                                    @"attention": attention,
                                    @"otherdesc": otherdesc
                                    };
        [kNetworkManager updateMortgageInfoWithParamters:paramters success:^(id responseObject) {
            if ([responseObject[@"code"] integerValue] == 200) {
                SISSObtainEvidenceShowViewController *vc = [[SISSObtainEvidenceShowViewController alloc] init];
                vc.ahbpId = self.ahbpId;
                
                vc.dataSource = self.obtainEvidenceEnrollViewModel.dataArr;
                [self.navigationController pushViewController:vc animated:YES];
            }
        } failed:^(NSError *error) {
            NSLog(@"%@",error);
        }];
    } else {
        NSDictionary *paramters = @{
                                    @"spId": [SISSUserAccount shared].spId,
                                    @"ahbpId": self.ahbpId,
                                    @"address": self.obtainEvidenceEnrollModel.address,
                                    @"bank": self.obtainEvidenceEnrollModel.bank,
                                    @"mortgage": self.obtainEvidenceEnrollModel.mortgage,
                                    @"obtainTime": self.obtainEvidenceEnrollModel.obtainTime,
                                    @"attention": attention,
                                    @"otherdesc": otherdesc
                                    };
        [kNetworkManager insertMortgageInfoWithParamters:paramters success:^(id responseObject) {
            if ([responseObject[@"code"] integerValue] == 200) {
                SISSObtainEvidenceShowViewController *vc = [[SISSObtainEvidenceShowViewController alloc] init];
                vc.ahbpId = self.ahbpId;
                
                vc.dataSource = self.obtainEvidenceEnrollViewModel.dataArr;
                [self.navigationController pushViewController:vc animated:YES];
            }
        } failed:^(NSError *error) {
            NSLog(@"%@",error);
        }];
    }
    
}


#pragma mark - UI
- (void)setupSubviews {
    [super setupSubviews];
    
    self.obtainEvidenceEnrollViewModel = [[SISSObtainEvidenceEnrollViewModel alloc] init];
    if (self.dataSource.count > 0) {
        self.obtainEvidenceEnrollViewModel.dataArr = self.dataSource.copy;
        self.obtainEvidenceEnrollViewModel.dataArr[0][1].cellType = 100;
    }
    SISSBaseTableView *tableView = [[SISSBaseTableView alloc] init];
    tableView.estimatedRowHeight = 44;
    tableView.rowHeight = UITableViewAutomaticDimension;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.obtainEvidenceEnrollViewModel registContractClass:tableView];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    self.obtainEvidenceEnrollViewModel.tableView = tableView;
    
    UIView *footerView = [[UIView alloc ] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 88)];
    
    UIButton *confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [confirmButton setTitle:@"确定" forState:UIControlStateNormal];
    [confirmButton setBackgroundColor:MAIN_COLOR];
    [confirmButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [confirmButton addTarget:self action:@selector(confirmButtonClickAction) forControlEvents:UIControlEventTouchUpInside];
    confirmButton.layer.cornerRadius = 4;
    confirmButton.layer.masksToBounds = YES;
    [self.view addSubview:confirmButton];
    self.confirmButton = confirmButton;
    
    [self.confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
        //        make.center.equalTo(footerView);
        //        make.width.mas_equalTo(SCREEN_WIDTH);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.mas_bottomLayoutGuideTop);
        make.height.mas_equalTo(44);
    }];
    
    self.tableView.tableFooterView = footerView;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self.view endEditing:YES];
}


@end
